package com.bruce.shop.dao.impl;

import com.bruce.shop.commons.utils.DBUtils;
import com.bruce.shop.dao.UserDao;
import com.bruce.shop.entity.User;
import java.util.List;

/**
 * @author BruceXia
 * @version 1.0.0
 * @description:用户Dao层的crud实现类
 * @date 2022/9/1718:47
 */
public class UserDaoImpl implements UserDao {
    @Override
    public Integer insert(User user) {
        String sql="insert into t_user(username,pass,sex,email,statu,activeCode,create_time)values(?,?,?,?,?,?,now())";
        return DBUtils.write(sql,user.getUsername(),user.getPass(),user.getSex(),user.getEmail(),user.getStatu(),user.getActiveCode());
    }

    @Override
    public Integer update(User user) {
        String sql = "update t_user set username = ?,email = ?,sex = ?,age=? where id = ?";
        return DBUtils.write(sql, user.getUsername(), user.getEmail(), user.getSex(), user
                .getAge(), user.getId());
    }

    @Override
    public Integer deleteById(Integer id) {
        String sql = "delete from t_user where id = ?";
        return DBUtils.write(sql, id);
    }

    @Override
    public User selectById(Integer id) {
        String sql = "select * from  t_user where id = ?";
        return DBUtils.selectOne(sql, User.class, id);
    }

    @Override
    public List list() {
        String sql = "select * from  t_user";
        return DBUtils.selectAll(sql, User.class);
    }

    @Override
    public Integer count() {

        String sql = "select count(1) from t_user";
        return DBUtils.readCount(sql);
    }

    @Override
    public List list(Integer size, Integer index) {

        String sql = "select * from  t_user limit ?,?";
        return DBUtils.selectAll(sql, User.class, index, size);
    }

    /**
     * 传入ids数组批量删除
     * @param ids
     * @return
     */
    @Override
    public Integer batchDel(List<String> ids) {
        //新建一个builder存放要传入的数据
        StringBuilder builder=new StringBuilder();

        builder.append("delete from t_user where id=(");

        //遍历的目的是计算有多少个数据要删，sql中添加对应数量的？
        for (int i= 0; i < ids.size(); i++) {
            if (i==ids.size()-1){
                builder.append("?");
            }else{
                builder.append("?,");
            }
        }

        builder.append("?");

        //toArray负责遍历集合
        return DBUtils.write(builder.toString(),ids.toArray());
    }


    @Override
    public User selectByName(String username) {
        String sql="select * from  t_user where username=?";
        return DBUtils.selectOne(sql,User.class,username);
    }

    @Override
    public User selectByCode(String code) {
        String sql="select * from t_user where activeCode=?";
        return DBUtils.selectOne(sql,User.class,code);
    }

    /**
     * 通过用户id修改状态值
     * @param id
     * @param i
     * @return
     */
    @Override
    public Integer updateStatu(Integer id, int i) {
        String sql="update t_user set statu=? where id=?";
        return DBUtils.write(sql,i,id);
    }
}
